from datetime import datetime

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from system.models import User


class CustomBackend(ModelBackend):
    '''
    重写登录验证，支持手机号码和用户名登录方式
    '''

    def authenticate(self, request, username=None, password=None, **kwargs):
        # noinspection PyBroadException
        try:
            user = User.objects.get(Q(username=username) | Q(phone=username))
            if user.check_password(password):
                user.last_login = datetime.now()
                user.save()
                return user
        except Exception as e:
            return None

# AUTHENTICATION_BACKENDS = (
#     '路径.CustomBackend',
# )
